my $services = fetchall_hash("services")
    or return;

my $chkconfig = in_path('chkconfig');
my $update_rcd = in_path('update-rc.d');

my %service_to_process = (
    autofs     => 'automount',
    bluetooth  => 'hcid',
    cups       => 'cupsd',
    haldaemon  => 'hald',
    ldap       => 'slapd',
    mcstrans   => 'mcstransd',
    mdmonitor  => 'mdadm',
    messagebus => 'dbus-daemon',
    nfslock    => 'rpc.statd',
    nfs        => 'rpc.mountd',
    rpcidmapd  => 'rpc.idmapd',
    rpcgssd    => 'rpc.gssd',
    rpcsvcgssd => 'rpc.svcgssd',
    syslog     => 'syslogd',
);

# where order is important, list the services here in descending priority
my %order = do { my $i = 1; map +($_ => $i++),
    qw(portmap nfslock nfs) };

foreach my $service (sort { ($order{$a} || 50) <=> ($order{$b} || 50) || $a cmp $b } keys %{ $services })
{
    my $info = $services->{$service};
    $info = { status => $info } unless ref $info;
    $info->{proc} ||= $service_to_process{$service} || $service;

    next unless -e "/etc/init.d/$service";

    command "chkconfig", $service, $info->{status} ? "on" : "off"
	if $chkconfig;

    command "update-rc.d", $service, $info->{status} ? "defaults" : "remove"
	if $update_rcd;

    my $running = 0;

    if ($info->{check})
    {
	$running =
	    0 == command $info->{check};
    }
    else
    {
	my $proc = $info->{proc};

	opendir DIR, "/proc";
	$running = !!grep /\b$proc\b/,
	    map readlink("/proc/$_/exe") || (),
		readdir DIR;
	close DIR;
    }

    command "/etc/init.d/$service", $info->{status} ? "start" : "stop"
	unless $running == $info->{status};
}

1;
